package com.woniuxy.special.utils;

import lombok.Data;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

//C00677232
//9cc19795f7d91cf2739f9a9b7e45d0f5
//api: https://106.ihuyi.com/webservice/sms.php?method=Submit
//        account: C75607634
//        password: c00d9bf9606e430362cb58cae05faed0
@Data
@Component
@ConfigurationProperties(prefix = "sms")
public class SMSUtil {
    private String api ;
    private String account ;
    private String password  ;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @RabbitListener(queues = {"registerCode","loginCode"})
    //@RabbitListener(bindings = {@QueueBinding(value = @Queue(""),exchange = @Exchange(""),key = {""})})
    @RabbitHandler
    public String sendCode(String str) throws Exception {
        //接收消息
        String[] strings = str.split(",");

        //使用hutool提供的Http工具发送请求
        HashMap<String, Object> params = new HashMap<>();
        params.put("account", account);
        params.put("password", password);
        params.put("mobile", strings[0]);
        params.put("format", "json");
        String code = String.valueOf((int) (Math.random() * 9000) + 1000);
        System.out.println(code);
        String content = "您的验证码是：" + code + "。请不要把验证码泄露给其他人。";
        params.put("content", content);

        redisTemplate.opsForValue().set(strings[1] + ":phone:" + strings[0], code, 5, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(strings[1] + ":phoneIs:" + strings[0], "", 5, TimeUnit.MINUTES);

        return null;
        //向第三方的接口发送请求
//        HttpResponse response = HttpRequest.post(api).form(params).execute();
//        String json = response.body();
//        String resultCode = JSONUtil.parseObj(json).get("code").toString();
//        System.out.println(resultCode);
//        if ("2".equals(resultCode)) {
//            //保存在redis
//            redisTemplate.opsForValue().set(strings[1] + ":phone:" + strings[0], code, 5, TimeUnit.MINUTES);
//            redisTemplate.opsForValue().set(strings[1] + ":phoneIs:" + strings[0], "", 5, TimeUnit.MINUTES);
//            return code;
//        } else {
//            throw new Exception("短信发送失败");
//        }
    }
}
